package com.example.driptip.ui.home;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.driptip.R;
import com.example.driptip.model.Alarm;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class AlarmAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int VIEW_TYPE_ALARM = 0;

    private final List<Alarm> alarms;
    private final Context context;
    private final AlarmCallback alarmCallback;
    private final StopCallback stopCallback;

    public interface AlarmCallback {
        void onAlarm(Alarm alarm, boolean isRepeating);
    }

    public interface StopCallback {
        void onStop(String alarmId);
    }

    public AlarmAdapter(Context context, List<Alarm> alarms, 
                       AlarmCallback alarmCallback, StopCallback stopCallback) {
        this.context = context;
        this.alarms = alarms;
        this.alarmCallback = alarmCallback;
        this.stopCallback = stopCallback;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_alarm, parent, false);
        return new AlarmViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Alarm alarm = alarms.get(position);
        bindAlarmViewHolder((AlarmViewHolder) holder, alarm);
    }

    private void bindAlarmViewHolder(AlarmViewHolder holder, Alarm alarm) {
        // 设置闹钟名称
        holder.nameView.setText(alarm.getName());

        // 根据闹钟类型显示不同的按钮布局
        if ("custom".equals(alarm.getType())) {
            holder.horizontalButtonsLayout.setVisibility(View.VISIBLE);
            holder.verticalButtonsLayout.setVisibility(View.GONE);
            holder.timePickerLayout.setVisibility(View.VISIBLE);
            
            // 设置时间选择器范围
            holder.hoursView.setMinValue(0);
            holder.hoursView.setMaxValue(23);
            holder.minutesView.setMinValue(0);
            holder.minutesView.setMaxValue(59);
            holder.secondsView.setMinValue(0);
            holder.secondsView.setMaxValue(59);

            // 设置当前值
            holder.hoursView.setValue(alarm.getHours());
            holder.minutesView.setValue(alarm.getMinutes());
            holder.secondsView.setValue(alarm.getSeconds());

            // 设置值改变监听器
            NumberPicker.OnValueChangeListener listener = (picker, oldVal, newVal) -> {
                if (picker == holder.hoursView) {
                    alarm.setHours(newVal);
                } else if (picker == holder.minutesView) {
                    alarm.setMinutes(newVal);
                } else if (picker == holder.secondsView) {
                    alarm.setSeconds(newVal);
                }
                // 立即更新按钮状态
                updateButtonState(holder, alarm);
            };

            holder.hoursView.setOnValueChangedListener(listener);
            holder.minutesView.setOnValueChangedListener(listener);
            holder.secondsView.setOnValueChangedListener(listener);

            // 设置水平按钮点击事件
            holder.onceButton.setOnClickListener(v -> {
                if (alarm.isRunning()) {
                    stopCallback.onStop(alarm.getId());
                } else {
                    alarmCallback.onAlarm(alarm, false);
                }
            });

            holder.repeatButton.setOnClickListener(v -> {
                if (alarm.isRunning()) {
                    alarm.setRepeating(false);
                    if (!alarm.isRepeating()) {
                        stopCallback.onStop(alarm.getId());
                    }
                } else {
                    alarmCallback.onAlarm(alarm, true);
                }
            });
        } else {
            holder.horizontalButtonsLayout.setVisibility(View.GONE);
            holder.verticalButtonsLayout.setVisibility(View.VISIBLE);
            holder.timePickerLayout.setVisibility(View.GONE);

            // 设置垂直按钮点击事件
            holder.onceButtonVertical.setOnClickListener(v -> {
                if (alarm.isRunning()) {
                    stopCallback.onStop(alarm.getId());
                } else {
                    alarmCallback.onAlarm(alarm, false);
                }
            });

            holder.repeatButtonVertical.setOnClickListener(v -> {
                if (alarm.isRunning()) {
                    alarm.setRepeating(false);
                    if (!alarm.isRepeating()) {
                        stopCallback.onStop(alarm.getId());
                    }
                } else {
                    alarmCallback.onAlarm(alarm, true);
                }
            });
        }

        // 设置闹钟图标点击事件（停止）
        holder.clockImage.setOnClickListener(v -> {
            if (alarm.isRunning()) {
                stopCallback.onStop(alarm.getId());
            }
        });

        // 更新按钮状态
        updateButtonState(holder, alarm);
    }

    private void updateButtonState(AlarmViewHolder holder, Alarm alarm) {
        boolean isRunning = alarm.isRunning();
        boolean isRepeating = alarm.isRepeating();
        
        // 检查时间是否为1秒或0秒
        boolean isTimeZero = false;
        if ("custom".equals(alarm.getType())) {
            isTimeZero = (alarm.getHours() == 0 && alarm.getMinutes() == 0 && alarm.getSeconds() == 0) ||
                        (alarm.getHours() == 0 && alarm.getMinutes() == 0 && alarm.getSeconds() == 1);
        } else {
            isTimeZero = alarm.getDuration() == 0;
        }
        
        // 更新水平按钮
        holder.onceButton.setText(isRunning ? "取消" : "单次");
        holder.onceButton.setEnabled(!isTimeZero);
        holder.repeatButton.setText(isRunning && isRepeating ? "结束" : "循环");
        holder.repeatButton.setEnabled(!isTimeZero);
        
        // 更新垂直按钮
        holder.onceButtonVertical.setText(isRunning ? "取消" : "单次");
        holder.onceButtonVertical.setEnabled(!isTimeZero);
        holder.repeatButtonVertical.setText(isRunning && isRepeating ? "结束" : "循环");
        holder.repeatButtonVertical.setEnabled(!isTimeZero);
        
        // 更新闹钟图标状态
        holder.clockImage.setEnabled(isRunning);
        holder.clockImage.setAlpha(isRunning ? 1.0f : 0.5f);
        
        // 更新倒计时显示
        holder.countdownView.setVisibility(isRunning ? View.VISIBLE : View.GONE);
    }

    public void updateCountdown(String alarmId, long millisUntilFinished) {
        for (int i = 0; i < alarms.size(); i++) {
            Alarm alarm = alarms.get(i);
            if (alarm.getId().equals(alarmId)) {
                notifyItemChanged(i, formatTime(millisUntilFinished));
                break;
            }
        }
    }

    public void stopAlarm(String alarmId) {
        for (int i = 0; i < alarms.size(); i++) {
            Alarm alarm = alarms.get(i);
            if (alarm.getId().equals(alarmId)) {
                alarm.setRunning(false);
                alarm.setRepeating(false);
                notifyItemChanged(i);
                break;
            }
        }
    }

    private String formatTime(long millis) {
        return String.format(Locale.getDefault(), "%02d:%02d:%02d",
            TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
            TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
    }


    @Override
    public int getItemCount() {
        return alarms.size();
    }

    static class AlarmViewHolder extends RecyclerView.ViewHolder {
        final TextView nameView;
        final LinearLayout timePickerLayout;
        final NumberPicker hoursView;
        final NumberPicker minutesView;
        final NumberPicker secondsView;
        final ImageView clockImage;
        final TextView countdownView;
        final Button onceButton;
        final Button repeatButton;
        final LinearLayout horizontalButtonsLayout;
        final LinearLayout verticalButtonsLayout;
        final Button onceButtonVertical;
        final Button repeatButtonVertical;

        AlarmViewHolder(View view) {
            super(view);
            nameView = view.findViewById(R.id.text_alarm_name);
            timePickerLayout = view.findViewById(R.id.layout_time_picker);
            hoursView = view.findViewById(R.id.picker_hours);
            minutesView = view.findViewById(R.id.picker_minutes);
            secondsView = view.findViewById(R.id.picker_seconds);
            clockImage = view.findViewById(R.id.image_clock);
            countdownView = view.findViewById(R.id.text_countdown);
            onceButton = view.findViewById(R.id.btn_once);
            repeatButton = view.findViewById(R.id.btn_repeat);
            horizontalButtonsLayout = view.findViewById(R.id.layout_buttons_horizontal);
            verticalButtonsLayout = view.findViewById(R.id.layout_buttons_vertical);
            onceButtonVertical = view.findViewById(R.id.btn_once_vertical);
            repeatButtonVertical = view.findViewById(R.id.btn_repeat_vertical);
        }
    }

} 